package com.mytest.mongotest;

import com.mongodb.MongoClient;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Filters;
import org.bson.Document;

import java.util.ArrayList;
import java.util.List;


/**
 * @author GLoRy
 * @date 2021/4/27 11:51
 */
public class MongoDbJdbc {
    public static void main(String[] args) {
        try {
            //连接mongodb服务
            MongoClient mongoClient = new MongoClient("localhost", 27017);

            //连接数据库
            MongoDatabase mongoDatabase = mongoClient.getDatabase("mycol");
            System.out.println("成功连接到mongo数据库");

            MongoCollection<Document> collection = mongoDatabase.getCollection("test");
            System.out.println("集合test选择成功");

            //插入文档
            /*
             * 1. 创建文档 org.bson.Document 参数为key-value的格式
             * 2. 创建文档集合List<Document>
             * 3. 将文档集合插入数据库集合中 mongoCollection.insertMany(List<Document>) 插入单个文档可以用 mongoCollection.insertOne(Document)
             */
            Document document = new Document("title", "MongoDB").
                    append("description", "databases").
                    append("likes", "100").
                    append("by", "Fly");
            List<Document> documents = new ArrayList<>();
            documents.add(document);
            collection.insertMany(documents);
            System.out.println("文档插入成功！");

            //检索所有文档
            /*
             * 1. 获取迭代器FindIterable<Document>
             * 2. 获取游标MongoCursor<Document>
             * 3. 通过游标遍历检索出的文档集合
             */
            FindIterable<Document> findIterable = collection.find();
            for (Document value : findIterable) {
                System.out.println(value);
            }

            //更新文档   将文档中likes=100的文档修改为likes=200
            collection.updateMany(Filters.eq("likes", 100), new Document("$set", new Document("likes", 200)));
            //检索查看结果
            FindIterable<Document> findIterable1 = collection.find();
            for (Document document1 : findIterable1) {
                System.out.println(document1);
            }

            //删除符合条件的第一个文档
            collection.deleteOne(Filters.eq("likes", 100));
            //删除所有符合条件的文档
            collection.deleteMany(Filters.eq("likes", 100));
            //检索查看结果
            FindIterable<Document> findIterable2 = collection.find();
            for (Document value1 : findIterable2) {
                System.out.println(value1);
            }
        } catch (Exception e) {
            System.out.println(e.getClass().getName() + ": " + e.getMessage());
        }
    }
}
